package com.ys.service.account.impl;

import com.alibaba.fastjson.JSON;
import com.ys.dto.EditDto;
import com.ys.entity.account.TcwAdvanceAccountDetail;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.account.TcwAdvanceAccountDetailMapper;
import com.ys.service.account.TcwAdvanceAccountDetailService;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 预支台账明细
 */
@Service("tcwAdvanceAccountDetailService")
public class TcwAdvanceAccountDetailServiceImpl implements TcwAdvanceAccountDetailService {
	private static final Logger logger = LoggerFactory.getLogger(TcwAdvanceAccountDetailServiceImpl.class);

	@Autowired
	private TcwAdvanceAccountDetailMapper tcwAdvanceAccountDetailMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	/**
	 * 新增
	 */
	@Override
	public R add(Map<String, Object> params, Long menuId) throws Exception {
		logger.info("传参："+params);
		//参数验证
		String errorMsg = checkParams(params,menuId);
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		Long userChangeId = null;
		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			userChangeId = tsUserChange.getId();//制单人变更信息
		}else {
			R.error("未查询到制单人信息！");
		}
		TcwAdvanceAccountDetail tcwAdvanceAccountDetail = JSON.parseObject(JSON.toJSONString(params), TcwAdvanceAccountDetail.class);
		tcwAdvanceAccountDetail.setCreateChangeId(userChangeId);
		tcwAdvanceAccountDetail.setTransferStatus(0);//划拨状态
		tcwAdvanceAccountDetailMapper.insert(tcwAdvanceAccountDetail);
		return R.ok(EditDto.closeAndReload());
		//return R.ok(AddDto.gotoEdit("/web/finance/tbAdvanceType/toEdit?id=" + tbAdvanceType.getId()));
	}

	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params, Long menuId) throws Exception {
		logger.info("传参："+params);
		//参数验证
		String errorMsg = checkParams(params,menuId);
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		TcwAdvanceAccountDetail entity = JSON.parseObject(JSON.toJSONString(params), TcwAdvanceAccountDetail.class);
		if(checkUtil.isNotNullByObject(entity.getUnitPrice()) && checkUtil.isNotNullByObject(entity.getProxyPrice())){
			BigDecimal unitPrice = entity.getUnitPrice();//成本价
			BigDecimal proxyPrice = entity.getProxyPrice();//代理价
			if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 && proxyPrice.compareTo(unitPrice)<0){
				return R.error("代理价不能低于成本价");
			}
		}

		tcwAdvanceAccountDetailMapper.update(entity);
		//return R.ok();
		return R.ok(EditDto.closeAndReload());
	}



	//删除
	@Override
	public void delTrue(Long id) throws Exception{
		tcwAdvanceAccountDetailMapper.deleteTrue(id);
	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCW_AdvanceAccountDetail",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		return backMsg;
	}




	//划拨，生成流水
	@Override
	public R doTransferFlow(Long id) throws Exception{
		TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail().setId(id).queryFirst();
		if(entity.getTransferStatus() ==1){
			return R.error("已划拨的明细不可再划拨");
		}

		Map<String,Object> info = new TcwAdvanceAccountDetail()
				.setId(id)
				.addLeftJoin("TCW_AdvanceAccount P ON P.Id = A.Pid")//预支账户管理
				.addLeftJoin("TS_OrganizationAccount OA ON OA.Orgid = P.Orgid")//部门账户绑定表
				.where("OA.Status = 1")
				.addField("OA.Vgsbm AS pVgsbm")//公司编码
				.addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = OA.Vgsbm")//运营公司表
				.addField("OCA.Vgsjc AS pVgsjc")//公司简称

				.addLeftJoin("THR_OperateCompanyApply OC ON OC.Vgsbm = A.Vgsbm")//运营公司表
				.addField("OC.Vgsjc AS vgsjc")//公司简称

				.addField("FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS saveTime")//保存时间

		.queryFirstMap();

		if(checkUtil.isNotNullByObject(info.get("vgsbm")) && checkUtil.isNotNullByObject(info.get("pVgsbm"))
				&& checkUtil.isNotNullByObject(info.get("proxyTotalPrice")) && checkUtil.isNotNullByObject(info.get("vjylx"))){
			BigDecimal proxyTotalPrice = new BigDecimal(info.get("proxyTotalPrice").toString());
			/*
			if(proxyTotalPrice.compareTo(BigDecimal.ZERO)>0){
				proxyTotalPrice = proxyTotalPrice.negate();
			}

			 */
			if(proxyTotalPrice.compareTo(BigDecimal.ZERO)!=0){
				Date saveTime = new Date();//DateUtil.parseYYYY_MM_dd_HH_mm_ss(info.get("saveTime").toString());

				String remark = "预支台账";//备注：预支台账+名称+代理价*数量+备注
				if(checkUtil.isNotNullByObject(info.get("detailName"))) remark +="，"+info.get("detailName").toString();
				if(checkUtil.isNotNullByObject(info.get("proxyPrice"))) remark +="，"+info.get("proxyPrice").toString();
				if(checkUtil.isNotNullByObject(info.get("quantity"))) remark +="*"+info.get("quantity").toString();
				if(checkUtil.isNotNullByObject(info.get("remark"))) remark +="，"+info.get("remark").toString();
				//新增流水
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						info.get("vgsbm").toString(),info.get("vgsjc").toString(),
						info.get("pVgsbm").toString(),info.get("pVgsjc").toString(),
						info.get("vjylx").toString(),proxyTotalPrice.negate(),saveTime, saveTime,
						remark,
						null,
						saveTime);
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						info.get("pVgsbm").toString(),info.get("pVgsjc").toString(),
						info.get("vgsbm").toString(),info.get("vgsjc").toString(),
						info.get("vjylx").toString(),proxyTotalPrice,saveTime, saveTime,null,
						remark,
						saveTime);
			}


			//修改划拨状态
			//TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail();
			entity.setId(id);
			entity.setTransferStatus(1);
			tcwAdvanceAccountDetailMapper.update(entity);
			return R.ok();
		}else {
			return R.error("运营公司、代理总额等信息不完整！");
		}


	}



	//复制
	@Override
	public R doCopy(Long id) throws Exception{
		TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			entity.setDetailType(0);
			entity.setTransferStatus(0);
			tcwAdvanceAccountDetailMapper.insert(entity);
		}
		return R.ok();

	}


	//删除
	@Override
	public R doDel(Long id) throws Exception{
		TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			if(entity.getDetailType() == 1 ){
				return R.error("已报销的明细不可删除");
			}
			if(entity.getTransferStatus() ==1){
				return R.error("已划拨的明细不可删除");
			}
			tcwAdvanceAccountDetailMapper.deleteTrue(id);
		}
		return R.ok();

	}



	//设置成本价
	@Override
	public R setUnitPrice(Long id, BigDecimal unitPrice) throws Exception{
		TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			if(entity.getDetailType() == 1 ){
				return R.error("已报销的明细不可修改成本价");
			}
			if(entity.getProxyPrice()!=null){
				BigDecimal proxyPrice = entity.getProxyPrice();//代理价
				if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 && proxyPrice.compareTo(unitPrice)<0){
					return R.error("代理价不能低于成本价");
				}
			}

			BigDecimal quantity = entity.getQuantity()!=null?entity.getQuantity():BigDecimal.ZERO;//数量
			//总额 = 单价 * 数量
			BigDecimal totalPrice = unitPrice.multiply(quantity);
			entity.setUnitPrice(unitPrice);
			entity.setTotalPrice(totalPrice);//总额
			tcwAdvanceAccountDetailMapper.update(entity);
		}
		return R.ok();

	}



	//设置代理价
	@Override
	public R setProxyPrice(Long id, BigDecimal proxyPrice) throws Exception{
		TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail().setId(id).queryFirst();
		if(entity!=null && entity.getStatus()!=null){
			if(entity.getTransferStatus() ==1){
				return R.error("已划拨的明细不可修改代理价");
			}
			BigDecimal unitPrice = entity.getUnitPrice();//成本价
			if(proxyPrice.compareTo(BigDecimal.ZERO)!=0 &&  proxyPrice.compareTo(unitPrice)<0){
				return R.error("代理价不能低于成本价");
			}
			BigDecimal quantity = entity.getQuantity()!=null?entity.getQuantity():BigDecimal.ZERO;//数量
			//代理总额 = 代理价 * 数量
			BigDecimal proxyTotalPrice = proxyPrice.multiply(quantity);
			entity.setProxyPrice(proxyPrice);
			entity.setProxyTotalPrice(proxyTotalPrice);//代理总额
			tcwAdvanceAccountDetailMapper.update(entity);
		}
		return R.ok();

	}



	//批量修改预支类型
	@Override
	public R setAdvanceType(Long id, String advanceTypeCode) throws Exception{
		TcwAdvanceAccountDetail entity = new TcwAdvanceAccountDetail().setId(id).queryFirst();
		if(entity!=null && entity.getTransferStatus()!=null){
			if(entity.getTransferStatus() ==1){
				return R.error("已划拨的明细不可修改");
			}

			entity.setAdvanceTypeCode(advanceTypeCode);
			tcwAdvanceAccountDetailMapper.update(entity);
		}
		return R.ok();

	}


}
